package org.springbus.habit.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springbus.habit.entity.AttributeInfo;
import org.springbus.habit.entity.Label;
import org.springbus.habit.service.AttributeInfoService;
import org.springbus.habit.service.LabelService;
import org.springbus.habit.web.entity.AttrValueEntity;
import org.springbus.habit.web.response.AttributeInfoResponse;
import org.springbus.habit.web.response.CommonResponse;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 平台属性管理 前端控制器
 * </p>
 *
 * @author Mr.Han
 * @since 2024-05-16
 */
@Tag(name = "平台属性管理")
@RestController
public class AttributeInfoController {

    @Resource
    private AttributeInfoService attributeInfoService;

    @Resource
    private LabelService labelService;

    @GetMapping("/admin/product/attrInfoList/{category1Id}/{category2Id}/{category3Id}")
    @Operation(summary = "分页查询平台属性管理")
    public CommonResponse<List<AttributeInfoResponse>> getPageList(
            @Parameter(description = "一级菜单ID", required = true) @PathVariable Long category1Id,
            @Parameter(description = "二级菜单ID", required = true) @PathVariable Long category2Id,
            @Parameter(description = "三级菜单ID", required = true) @PathVariable Long category3Id) {
        int level = getCategoryLevel(category1Id, category2Id, category3Id);
        Long categoryId;
        if (level == 1) {
            categoryId = category1Id;
        } else if (level == 2) {
            categoryId = category2Id;
        } else {
            categoryId = category3Id;
        }

        List<AttributeInfo> list = attributeInfoService.list(new QueryWrapper<AttributeInfo>()
                .eq("category_id", categoryId).eq("deleted", false));
        if (CollectionUtils.isEmpty(list)) {
            return new CommonResponse<>(Lists.newArrayList());
        }

        List<AttributeInfoResponse> responseList = list.stream().map(e -> {
            ArrayList<AttrValueEntity> attrValueList = Lists.newArrayList();
            if (StringUtils.isNotBlank(e.getLabelId())) {
                List<Long> labelIds = Lists.newArrayList();
                String[] split = e.getLabelId().split(",", -1);
                for (String s : split) {
                    labelIds.add(Long.valueOf(s));
                }
                List<Label> labels = labelService.listByIds(labelIds);
                attrValueList = labels.stream().map(label -> {
                    AttrValueEntity attrValueEntity = new AttrValueEntity();
                    attrValueEntity.setAttrId(e.getId());
                    attrValueEntity.setId(label.getId());
                    attrValueEntity.setValueName(label.getName());
                    return attrValueEntity;
                }).collect(Collectors.toCollection(ArrayList::new));
            }
            return new AttributeInfoResponse().setAttrName(e.getName())
                    .setAttrValueList(attrValueList)
                    .setCategoryId(categoryId)
                    .setCategoryLevel((long) level)
                    .setId(e.getId());
        }).toList();
        return new CommonResponse<>(responseList);
    }


//    @PutMapping("/admin/product/modified/attrInfo")
//    @Operation(summary = "修改属性名称以及属性值")
//    public CommonResponse<Boolean> modifiedAttrInfo(@RequestBody AttributeInfoResponse request) {
//        List<AttrValueEntity> attrValueList = request.getAttrValueList();
//        List<Label> list = Optional.ofNullable(attrValueList).orElse(Lists.newArrayList()).stream()
//                .filter(e -> null == e.getId()).map(e -> new Label()
//                        .setAttributeId(request.getId())
//                        .setName(e.getValueName())
//                        .setIsChecked(false)
//                        .setDeleted(false)
//                        .setGmtCreate(new Date())).toList();
//
//        labelService.saveBatch(list);
//        List<Label> labels = labelService.list(new QueryWrapper<Label>().eq("attribute_id", request.getId())
//                .eq("deleted", false));
//        Optional.ofNullable(labels).filter()
//                .map(e -> {
//            StringBuilder builder = new StringBuilder();
//            for (int i = 0; i < e.size(); i++) {
//                if (i > 0) {
//                    builder.append(",");
//                }
//                builder.append(e.get(i).getId());
//            }
//            return builder.toString();
//        }).ifPresent(ids -> attributeInfoService.update(new AttributeInfo().setLabelId(ids).setName(request.getAttrName()),
//                new QueryWrapper<AttributeInfo>().eq("id", request.getId())));
//        return new CommonResponse<>(true);
//    }

    @DeleteMapping("/admin/product/attr/remove/{id}")
    @Operation(summary = "删除属性")
    public CommonResponse<Boolean> removeAttr(@Parameter(description = "属性ID", required = true) @PathVariable String id) {
        List<Label> labels = labelService.list(new QueryWrapper<Label>().eq("attribute_id", id));
        attributeInfoService.update(new AttributeInfo().setDeleted(true).setGmtModified(new Date()), new QueryWrapper<AttributeInfo>()
                .eq("id", id).eq("deleted", false));
        List<Label> list = Optional.ofNullable(labels).orElse(Lists.newArrayList()).stream().map(e -> new Label().setId(e.getId())
                .setDeleted(true).setGmtModified(new Date())).toList();
        labelService.updateBatchById(list);
        return new CommonResponse<>(true);
    }

    @PostMapping("admin/product/save/attrInfo")
    @Operation(summary = "保存属性")
    public CommonResponse<Boolean> saveAttrInfo(@RequestBody AttributeInfoResponse request) {
        List<AttrValueEntity> attrValueList = request.getAttrValueList();
        List<Label> newValueList = Lists.newArrayList();
        if (Objects.nonNull(request.getId())) {
            AttributeInfo info = attributeInfoService.getById(request.getId());
            if (StringUtils.isNotBlank(info.getLabelId())) {
                String[] split = info.getLabelId().split(",");
                List<Long> ids = Stream.of(split).map(Long::valueOf).toList();
                labelService.removeBatchByIds(ids);
            }
            newValueList = Optional.ofNullable(attrValueList).orElse(Lists.newArrayList()).stream()
                    .filter(e -> Objects.nonNull(e.getId())).map(e -> new Label()
                            .setId(e.getId())
                            .setAttributeId(info.getId())
                            .setName(e.getValueName())
                            .setIsChecked(false)
                            .setDeleted(false)
                            .setGmtModified(new Date())).toList();
            labelService.updateBatchById(newValueList);
        }
        List<Label> list = new ArrayList<>(Optional.ofNullable(attrValueList).orElse(Lists.newArrayList()).stream()
                .filter(e -> null == e.getId()).map(e -> new Label()
                        .setAttributeId(e.getAttrId())
                        .setName(e.getValueName())
                        .setIsChecked(false)
                        .setDeleted(false)
                        .setGmtCreate(new Date())).toList());

        if (CollectionUtils.isNotEmpty(list)) {
            labelService.saveBatch(list);
        }

        list.addAll(newValueList);
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            if (i > 0) {
                builder.append(",");
            }
            builder.append(list.get(i).getId());
        }
        AttributeInfo entity = new AttributeInfo()
                .setCategoryId(request.getCategoryId())
                .setName(request.getAttrName())
                .setLabelId(builder.toString())
                .setDeleted(false)
                .setGmtCreate(new Date());
        attributeInfoService.save(entity);
        List<Label> labelList = list.stream().map(e -> new Label()
                .setId(e.getId())
                .setAttributeId(entity.getId())
                .setGmtModified(new Date())).toList();
        labelService.updateBatchById(labelList);
        return new CommonResponse<>(true);
    }

    private Integer getCategoryLevel(Long category1Id, Long category2Id, Long category3Id) {
        if (null != category1Id && null != category2Id && null != category3Id) {
            return 3;
        } else if (null != category1Id && null != category2Id) {
            return 2;
        } else {
            return 1;
        }
    }
}
